import React from 'react'
import SyntaxHighlighter from 'react-syntax-highlighter'
import { docco } from 'react-syntax-highlighter/dist/cjs/styles/hljs'

const CoderViewer = ({ codeText, title, id, width }) => {
    const copyToClipboard = () => {
        // 将 codeText 拷贝进用户剪贴板
        if (typeof navigator !== 'undefined') {
            try {
                navigator.clipboard.writeText(codeText)
            } catch (e) {
                alert('copy failed')
            }
        }
    }

    return (
        <div
            style={{
                overflow: 'visible',
                width: width || '100%',
                boxSizing: 'border-box',
                position: 'relative',
            }}
        >
            <div style={{ textAlign: 'center' }}>
                <h2>{title}</h2>
                <button onClick={copyToClipboard}>copy</button>
            </div>
            <div
                id={id}
                style={{
                    position: 'relative',
                    marginLeft: '20px',
                    marginRight: '20px',
                    overflow: 'visible',
                }}
            >
                <SyntaxHighlighter
                    language="java"
                    style={docco}
                    showLineNumbers
                    wrapLines
                    lineProps={lineNumber => {
                        let style = { width: '100%' }
                        return { style, id: `${id}-line-${lineNumber}` }
                    }}
                >
                    {codeText}
                </SyntaxHighlighter>
            </div>
        </div>
    )
}

export default CoderViewer
